﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System;
using System.Collections.Generic;

using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MX.Core.ORM
{
    public class DatabaseConfig
    {
        static bool isInit = false;
        //字符串对应的数据库KEY
        static Dictionary<int, string> connKeyStringPool = new Dictionary<int, string>();
        //连接字符串对于数据库KEY
        static Dictionary<int, ConnectionStringSettings> connStringPool = new Dictionary<int, ConnectionStringSettings>();
        static DatabaseConfig()
        {

        }

        /// <summary>
        /// 配置枚举对于的KEY,在第一次调用数据库连接前配置，后配置无效
        /// </summary>
        public static void RegisterStringKey(object databse, string key, string configFile = "appsettings.json",string section = "ConnectionStrings")
        {
            connKeyStringPool[Convert.ToInt32(databse)] = key;
            RegisterString(configFile, section);
        }

        /// <summary>
        /// 载入连接字符串
        /// </summary>
		private static void RegisterString(string configFile= "appsettings.json", string section = "ConnectionStrings")
        { 
            var configuration = new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = configFile, ReloadOnChange = false }).Build();
            foreach (var item in connKeyStringPool)
            {
                var connectionStringCollection = configuration.GetSection(section).Get<ConnectionStringSettingsCollection>();
                ConnectionStringSettings connStr = connectionStringCollection[item.Value];
                if (connStr == null)
                {
                    throw new NotImplementedException(String.Format("请为KEY：{0}配置对应的连接字符串", item.Value));
                }
                else
                {
                    connStringPool[item.Key] = connStr;
                }
            }

        }

        /// <summary>
        /// 获取连接字符串配置
        /// </summary>
        /// <param name="database"></param>
        /// <returns></returns>
		public static ConnectionStringSettings GetConnectionString(int database)
        {

            return connStringPool[database];
        }
    }
}
